package com.thp.bigdata.secondarySort;

import java.io.IOException;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.DoubleWritable;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.NullWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;

public class SecondarySort {
	
	
	/**
	 * 	Order_0000001,Pdt_01,222.8
		Order_0000001,Pdt_05,25.8
		Order_0000002,Pdt_05,325.8
		Order_0000002,Pdt_03,522.8
		Order_0000002,Pdt_04,122.4
		Order_0000003,Pdt_01,222.8
	 * 
	 * 由于Orderbean定义了compareTo方法，所以在shuffle阶段就会进行排序
	 * 接下来就是要使用自定义的partitioner进行分区
	 * 我们进行分区的目的是要将相同的id的OrderBean发往相同的partition进行处理
	 * 每一个partition拿到的都是相同的id的OrderBean
	 * 但是key却不是一样的，我们现在要欺骗parition，让它以为相同id的OrderBean都是相同的key
	 * 那么处理的时候，就会只保留第一个key，就是我们之前排序好放在最前面的key就是这个id下的订单数量最高的OrderBean
	 * 
	 */
	static class SecondarySortMapper extends Mapper<LongWritable, Text, OrderBean, NullWritable> {
		OrderBean bean = new OrderBean();
		@Override
		protected void map(LongWritable key, Text value,Context context)
				throws IOException, InterruptedException {
			String line = value.toString();
			System.out.println(line);
			String[] fields = line.split(",");
			// System.out.println(fields[0] + " -- " + fields[2]);
			bean.set(new Text(fields[0]), new DoubleWritable(Double.parseDouble(fields[2])));
			// System.out.println(bean.getItemId());
			context.write(bean, NullWritable.get());
		}
	}
	
	static class SecondarySortReducer extends Reducer<OrderBean, NullWritable, OrderBean, NullWritable> {
		@Override
		protected void reduce(OrderBean key, Iterable<NullWritable> values, Context context)
				throws IOException, InterruptedException {
			context.write(key, NullWritable.get());
		}
	}
	
	public static void main(String[] args) throws IllegalArgumentException, IOException, ClassNotFoundException, InterruptedException {
		Configuration conf = new Configuration();
		Job job = Job.getInstance(conf);
		
		job.setJarByClass(SecondarySort.class);
		
		job.setMapperClass(SecondarySortMapper.class);
		job.setReducerClass(SecondarySortReducer.class);
		
		
		job.setOutputKeyClass(OrderBean.class);
		job.setOutputValueClass(NullWritable.class);
		
		FileInputFormat.setInputPaths(job, new Path("f:/order/input"));
		FileOutputFormat.setOutputPath(job, new Path("f:/order/output"));
		
		job.setGroupingComparatorClass(ItemIdGroupingComparator.class);
		job.setPartitionerClass(ItemIdPartitioner.class);
		job.setNumReduceTasks(3);
		
		System.exit(job.waitForCompletion(true) ? 0 : 1);
	}
	
	
}
